package com.yicong.ants.utils;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.widget.ImageView;

import androidx.databinding.BindingAdapter;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.request.RequestOptions;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.util.CallBacks;
import com.yicong.ants.bean.task.TaskInfo;
import com.yicong.ants.manager.holder.GlideRoundTransform;

import java.io.File;
import java.math.BigDecimal;

/**
 * 图片加载工具类
 */
public class GlideUtils {

    public static RequestOptions getRequestOptions(int placeholder, int error, int round) {
        RequestOptions options = new RequestOptions()
                .placeholder(placeholder)
                .error(error)
                .centerCrop();
        if (round > 0) {
            options.transform(new GlideRoundTransform(round));
        }
        return options;
    }

    public static RequestOptions getRequestOptions(int round) {
        return new RequestOptions()
                .centerCrop().transform(new GlideRoundTransform(round));
    }

    public static RequestOptions getRequestOptions(int placeholder, int error) {
        return getRequestOptions(placeholder, error, 0);
    }

    //任务专用
    @BindingAdapter(value = {"listBean", "status", "unit"}, requireAll = false)
    public static void loadImage(ImageView iv, TaskInfo.ListBean bean, String status, String unit) {
        if (bean.getIcon_url() == null || "".equals(bean.getIcon_url())) {
            int intRes = bean.getBg_drawable(unit + (status == null ? "" : status));
            loadRound(iv, intRes, null);
        } else {
            loadRound(iv, bean.getIcon_url(), null);
        }
    }

    //进行中任务专用
    @BindingAdapter(value = {"ingBean", "status", "unit"}, requireAll = false)
    public static void loadImage(ImageView iv, TaskInfo.IngBean bean, String status, String unit) {
        if (bean.getIcon_url() == null || "".equals(bean.getIcon_url())) {
            int intRes = bean.getBg_drawable(unit + (status == null ? "" : status));
            loadRound(iv, intRes, null);
        } else {
            loadRound(iv, bean.getIcon_url(), null);
        }
    }

    public static void loadRound(ImageView iv, String url, int round) {
        loadRound(iv, url, getRequestOptions(round));
    }

    public static void loadRound(ImageView iv, int resInt, RequestOptions options) {
        if (resInt == 0 || null == iv) {
            return;
        }
        RequestBuilder<Drawable> builder = Glide.with(iv).load(resInt);
        if (null == options) {
            builder.into(iv);
        } else {
            builder.apply(options).into(iv);
        }
    }

    public static void loadRound(ImageView iv, String url, RequestOptions options) {
        if (TextUtils.isEmpty(url) || null == iv) {
            return;
        }
        RequestBuilder<Drawable> builder = Glide.with(iv).load(url);
        if (null == options) {
            builder.into(iv);
        } else {
            builder.apply(options).into(iv);
        }
    }

    /**
     * 获取Glide造成的缓存大小
     *
     * @return CacheSize
     */
    public static String getCacheSize(Context context) {
        try {
            return getFormatSize(getFolderSize(new File(context.getCacheDir() + "/image_manager_disk_cache")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取指定文件夹内所有文件大小的和
     *
     * @param file file
     * @return size
     * @throws Exception
     */
    private static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (File aFileList : fileList) {
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 删除指定目录下的文件，这里用于缓存的删除
     *
     * @param filePath       filePath
     * @param deleteThisPath deleteThisPath
     */
    private static void deleteFolderFile(String filePath, boolean deleteThisPath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {
                    File files[] = file.listFiles();
                    for (File file1 : files) {
                        deleteFolderFile(file1.getAbsolutePath(), true);
                    }
                }
                if (deleteThisPath) {
                    if (!file.isDirectory()) {
                        file.delete();
                    } else {
                        if (file.listFiles().length == 0) {
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 格式化单位
     *
     * @param size size
     * @return size
     */
    private static String getFormatSize(double size) {

        double kiloByte = size / 1024;
        if (kiloByte == 0) {
            return "0B";
        }
        if (kiloByte < 1) {
            return size + "B";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);

        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }

    public static void clearCache(Context context, CallBacks.Int callBack) {
        new Thread(() -> {
            Glide.get(context).clearDiskCache();
            UiHelper.runOnUiThread(() -> callBack.onCallBack(0));
        }).start();
    }
}
